package servlet.usuario;

import bbdd.Conexion;
import bean.BeanSession;
import utilidades.Encriptacion;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by juanky on 25/11/14.
 */
public class crearUsuario extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        Encriptacion encriptacion = new Encriptacion();
        Conexion cnx = new Conexion();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String select = "select id from usuarios where nick=?";
        String insert = "insert into usuarios (nick, password, email, rol) values (?,?,?,3)";
        try {
            ps = cnx.getConexion(select);
            ps.setString(1, request.getParameter("username_new_txt"));
            rs = ps.executeQuery();
            if (rs.next()) {
                response.getWriter().write("<script type='text/javascript'>alert('Ya existe ese nombre de usuario');<script>");
            } else {
                rs.close();
                ps.close();
                ps = cnx.getConexion(insert, new String[]{"id"});
                ps.setString(1, request.getParameter("username_new_txt"));
                ps.setString(2, encriptacion.encriptar(request.getParameter("password_new_txt")));
                ps.setString(3, request.getParameter("email_txt"));
                ps.execute();
                rs = ps.getGeneratedKeys();
                if (rs.next()) {
                    BeanSession bean = new BeanSession();
                    if (bean.login(request.getParameter("username_new_txt"), request.getParameter("password_new_txt"))) {
                        request.getSession().setAttribute("bean", bean);
                        response.sendRedirect(request.getContextPath() + "/index.jsp");
                    } else {
                        response.getWriter().write("<script type='text/javascript'>alert('Su usuario ha sido creado correctamente.\nPuede iniciar sesion');<script>");
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Conexion.close(cnx, ps, rs);
        }
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doPost(request, response);
    }
}
